using System;
using System.Xml.Serialization;

namespace SQLRunnerLib.VersionCheck
{
	/// <summary>
	/// Summary description for Version.
	/// </summary>
	[Serializable]
	public class AppVersion
	{
		#region Private Instances

		private int _major;
		private int _minor;
		private int _build;
		private int _revision;

		#endregion
		#region Properties

		[XmlElement()]
		public int Major
		{
			get { return _major; }
			set
			{
				CheckPortionValue(value, "Mayor");
				_major = value;	
			}
		}

		private void CheckPortionValue(int value, string method)
		{
			if (value < 0) throw new ArgumentException("Version portion can not be negative", method);
		}

		[XmlElement()]
		public int Minor
		{
			get { return _minor; }
			set
			{
				CheckPortionValue(value, "Minor");
				_minor = value;
			}
		}

		[XmlElement()]
		public int Build
		{
			get { return _build; }
			set
			{
				CheckPortionValue(value, "Build");
				_build = value;
			}
		}

		[XmlElement()]
		public int Revision
		{
			get { return _revision; }
			set
			{
				CheckPortionValue(value, "Revision");
				_revision = value;
			}
		}

		#endregion

		public AppVersion(){}

		public int CompareTo(object obj)
		{			
			AppVersion other = obj as AppVersion;
			if ( other == null ) throw new ArgumentException("object is not a Version");
			return TransforToSystemVersion(this).CompareTo(TransforToSystemVersion(other));
		}

		public static AppVersion ConvertFromSystemVersion(System.Version ver)
		{
			if ( ver == null ) 
                return null;

			AppVersion appVer = new AppVersion();
			appVer.Major = ver.Major; appVer.Minor = ver.Minor;
			appVer.Build = ver.Build; appVer.Revision = ver.Revision;
			return appVer;
		}

		public static System.Version TransforToSystemVersion(AppVersion appVer)
		{
			return new System.Version(appVer.Major, appVer.Minor, appVer.Build, appVer.Revision);
		}

		public override string ToString()
		{
			return TransforToSystemVersion(this).ToString();
		}

	}
}
